<template>
  <div>
    <van-popup v-model="showDialog" :overlay="true" position="bottom">
      <alipay-case ref="alipayCases"/>
      <div class="dialog">
        <div class="dialog-title">
          <span v-if="!payType">支付方式</span>
          <span v-else>充值方式</span>
          <div class="fr icon-close" @click="showDialog = false">
            <svg-icon icon-class="icon_close2" />
          </div>
        </div>
        <div class="dialog-content">
          <van-radio-group v-model="paymentWay">
            <div v-if="!payType" class="item">
              <svg-icon class="icon" icon-class="icon_balance" />
              <span class="txt">余额支付</span>
              <span class="price font-colorRed">&yen; {{ parseFloat(balance).toFixed(getitem.item_price_p) }}</span>
              <van-button v-if="parseFloat(balance) < parseFloat(not_pay_fee)" class="btn-mini" size="mini" @click="clickToRecharge">去充值</van-button>
              <div class="fr"><van-radio name="1"/></div>
            </div>
            <div v-if="is_weixin_open == 1" class="item">
              <svg-icon class="icon" icon-class="icon_weChat" />
              <span class="txt">微信支付</span>
              <div class="fr"><van-radio name="2"/></div>
            </div>
            <div v-if="is_alipay_open == 1" class="item">
              <svg-icon class="icon font-colorBlue" icon-class="icon_alipay" />
              <span class="txt">支付宝支付</span>
              <div class="fr"><van-radio name="4"/></div>
            </div>
            <div v-if="getfund.is_open_offline == 1" class="item">
              <svg-icon class="icon" icon-class="icon_offline" />
              <span class="txt">线下支付</span>
              <div class="fr"><van-radio name="3"/></div>
            </div>
            <div v-if="payType && is_weixin_open !==1 && is_alipay_open !== 1&& getfund.is_open_offline !== 1" class="item">
              后台没有设置任何付款方式，请联系商家开通付款
            </div>
          </van-radio-group>
        </div>
        <div class="dialog-bottom">
          <div class="btn org-bg" @click="payForEvent">立即支付</div>
        </div>
      </div>
    </van-popup>

    <van-popup v-model="showPayDialog" :overlay="true" position="bottom">
      <div class="dialog">
        <div class="dialog-title">
          <span v-if="paymentWay == 1">余额支付</span>
          <span v-if="paymentWay == 2">微信支付</span>
          <span v-if="paymentWay == 3">线下支付</span>
          <span v-if="paymentWay == 4">支付宝支付</span>
          <div class="fr icon-close" @click="showPayDialog = false">
            <svg-icon icon-class="icon_close2" />
          </div>
        </div>
        <div class="dialog-content2">
          <!--todo:充值时不显示-->
          <div v-if="!payType" class="waitPay">
            <span class="label">待付款：</span>
            <span class="unit font-colorRed">&yen;</span> <span class="price font-colorRed">{{ parseFloat(not_pay_fee).toFixed(getitem.item_price_p) }}</span>
            <!--余额付款时显示余额-->
            <div v-if="paymentWay == 1" class="inline">
              <span class="balance-num">余额：</span>
              <span class="unit">&yen;</span><span class="price"> {{ parseFloat(balance).toFixed(getitem.item_price_p) }}</span>
            </div>
          </div>
          <div class="item">
            <div v-if="paymentWay == 1" class="balance">
              <van-field v-model="formData.balance_fee" label="现金账户" placeholder="请输入金额"/>
            </div>
            <div v-if="paymentWay == 4 || paymentWay == 2" class="balance">
              <van-field v-model="formData.pay_fee" label="付款金额" placeholder="请输入金额"/>
            </div>
            <van-cell-group v-if="paymentWay == 3">
              <van-field v-model="formData.pay_fee" label="付款金额(元)" placeholder="请输入付款金额"/>
              <div class="select">
                <van-field
                  v-model="shopAccountInfo.name"
                  readonly
                  label="收款账号"
                  placeholder="请选择收款账号"/>
                <mu-select
                  v-model="formData.shop_account_number_id"
                  class="select-con"
                  underline-color="#eee"
                  @change="onSelect">
                  <mu-option
                    v-for="(item) in accountList"
                    :key="item.shop_account_number_id"
                    :label="`${item.account_name} ( ${item.account_number} )`"
                    :value="item.shop_account_number_id"/>
                </mu-select>
              </div>
              <van-field v-model="shopAccountInfo.shop_account_name" class="disabled" disabled label="账户名称" placeholder="账户名称" />
              <van-field v-model="shopAccountInfo.shop_account_bank" class="disabled" disabled label="开户银行" placeholder="开户银行" />
              <van-field v-model="shopAccountInfo.shop_account" class="disabled" disabled label="银行账户" placeholder="银行账户" />
              <van-field
                v-model="formData.pay_time"
                readonly
                label="日期"
                placeholder="请选择日期"
                @click="openDateTime"/>
              <van-field v-model="formData.remark" label="备注" type="textarea" placeholder="请输入备注" />
            </van-cell-group>
          </div>
        </div>
        <div v-if="payType && paymentWay == 4" class="dialog-bottom" @click="rechargeOnlineEvent(2)">
          <div class="btn org-bg">去支付宝充值</div>
        </div>
        <div v-else-if="payType" class="dialog-bottom" @click="rechargeEvent">
          <div class="btn org-bg">确认充值</div>
        </div>
        <div v-else-if="paymentWay == 4" class="dialog-bottom" @click="paymentOnline(3)">
          <div class="btn org-bg">去支付宝支付</div>
        </div>
        <div v-else-if="paymentWay == 2" class="dialog-bottom" @click="paymentOnline(4)">
          <div class="btn org-bg">去微信支付</div>
        </div>
        <div v-else class="dialog-bottom" @click="paymentEvent">
          <div class="btn org-bg">确认支付</div>
        </div>

      </div>
    </van-popup>
    <van-popup v-model="showDateDialog" :overlay="true" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        :formatter="formatter"
        type="datetime"
        @confirm="sureDateTimer"
        @cancel="cancelDateTimer"/>
    </van-popup>
  </div>
</template>

<script>
import { isWechat } from '@/utils/index'
import { mapGetters } from 'vuex'
import alipayCase from './alipayCase'
import { payOrderGathering, PostOnlinePayOrder } from '@/api/order'
import { getAccountList, addUserRecharge, postAddRechargeByPay } from '@/api/capital'
import { getUserAccountInfo } from '@/api/balance'
import { getPayInfo } from '@/api/system'
export default {
  name: 'PaymentDialog',
  components: {
    alipayCase
  },
  props: {
    payType: {
      type: String,
      default: undefined
    }
  },
  data() {
    return {
      currentDate: new Date(),
      accountList: [],
      showDialog: false,
      showPayDialog: false,
      showDateDialog: false,
      paymentWay: undefined,
      balance: 0, // 余额
      not_pay_fee: '', // 待付款金额
      shopAccountInfo: {
        shop_account_name: '',
        shop_account_bank: '',
        shop_account: '',
        name: ''
      },
      // 支付数据
      formData: {
        order_id: '',
        balance_fee: 0,
        pay_fee: 0,
        pay_time: '',
        shop_account_number_id: '',
        remark: ''
      },
      is_alipay_open: 0,
      is_weixin_open: 0
    }
  },
  computed: {
    ...mapGetters([
      'getfund',
      'getitem'
    ])
  },
  watch: {
    'showDialog': function() {
      if (this.showDialog) {
        this.$parent.payType = undefined
      }
    }
  },
  created() {
    this.formData.pay_time = this.sureDateTimer(new Date())
    this.getAccountListFn()
    this.getUserAccountInfoFn()
    this.isOpenonlinePaymentWay()
  },
  methods: {
    // 点击跳转到充值
    clickToRecharge() {
      this.$parent.payType = 'reCharge'
    },
    // 打开时间插件弹层
    openDateTime() {
      this.showDateDialog = true
    },
    // 取消选择时间
    cancelDateTimer() {
      this.showDateDialog = false
    },
    // 处理时间选择器内容格式
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } else if (type === 'hour') {
        return `${value}时`
      } else if (type === 'minute') {
        return `${value}分`
      }
    },
    // 确认时间事件(格式化时间)
    sureDateTimer(val) {
      // 年
      const year = val.getFullYear()
      // 月
      const month = val.getMonth() + 1 < 10 ? ('0' + (val.getMonth() + 1)) : val.getMonth() + 1
      // 日
      const day = val.getDate() < 10 ? ('0' + val.getDate()) : val.getDate()
      // 时
      const hours = val.getHours() < 10 ? ('0' + val.getHours()) : val.getHours()
      // 分
      const minute = val.getMinutes() < 10 ? ('0' + val.getMinutes()) : val.getMinutes()
      // 秒
      const second = val.getSeconds() < 10 ? ('0' + val.getSeconds()) : val.getSeconds()
      const newDate = year + '-' + month + '-' + day + ' ' + hours + ':' + minute + ':' + second
      console.log(val, newDate)
      this.currentDate = val
      this.formData.pay_time = newDate
      this.showDateDialog = false
    },
    // 选择了支付之后点击支付按钮
    payForEvent() {
      const paymentWay = this.paymentWay
      if (paymentWay === '1') {
        this.clearData()
        this.showPayDialog = true
        this.formData.balance_fee = this.not_pay_fee
      } else if (paymentWay === '2') {
        this.clearData()
        this.showPayDialog = true
        this.formData.pay_fee = this.not_pay_fee
        console.log('微信支付')
      } else if (paymentWay === '3') {
        this.clearData()
        this.formData.pay_fee = this.not_pay_fee
        this.formData.pay_time = ''
        // 默认选中第一个账户
        if (this.accountList.length > 0) {
          this.formData.shop_account_number_id = this.accountList[0].shop_account_number_id
          this.onSelect()
          this.showPayDialog = true
        } else {
          this.$toast.fail({
            message: '商家未设置收款账号,请联系商家！',
            duration: 2500
          })
        }
      } else if (paymentWay === '4') {
        this.clearData()
        this.showPayDialog = true
        this.formData.pay_fee = this.not_pay_fee
        console.log('支付宝支付')
      }
    },
    // 获取收款账户列表
    getAccountListFn() {
      getAccountList().then(res => {
        const data = res.data
        if (data.status_code === 200) {
          const accountList = data.data.list
          const arr = []
          accountList.forEach(item => {
            const obj = item
            obj.name = item.account_name + '(' + item.account_number + ')'
            arr.push(obj)
          })
          this.accountList = arr
        } else {
          this.accountList = [{
            name: '暂无收款账户'
          }]
        }
      })
    },
    // 获取余额信息
    getUserAccountInfoFn() {
      getUserAccountInfo().then(res => {
        const data = res.data
        if (data.status_code === 200) {
          this.balance = data.data.balance
        }
      })
    },
    // 创建付款单
    paymentEvent() {
      this.$toast.loading({
        duration: 10000,
        mask: true,
        message: '正在提交...'
      })
      const formData = this.formData
      if (this.paymentWay === '1') {
        formData.pay_time = undefined
      }
      payOrderGathering(formData).then(res => {
        this.$toast.clear()
        const data = res.data
        if (data.status_code === 200) {
          this.showPayDialog = false
          this.showDialog = false
          this.$toast.success({
            message: data.message,
            duration: 1500
          })
          setTimeout(() => {
            window.location.reload()
          }, 1000)
        } else {
          this.$toast.fail({
            message: data.message,
            duration: 1500
          })
        }
      })
    },
    // 判断是否开启了微信和支付宝支付
    isOpenonlinePaymentWay() {
      getPayInfo().then(res => {
        const data = res.data
        if (data.status_code === 200) {
          this.is_alipay_open = data.data.is_alipay_open
          this.is_weixin_open = data.data.is_weixin_open
        }
      })
    },
    // 在线支付
    paymentOnline(type) {
      this.$toast.loading({
        duration: 10000,
        mask: true,
        message: '正在跳转...'
      })
      const formData = this.formData
      const dataset = {
        order_id: formData.order_id,
        type: type,
        pay_fee: formData.pay_fee
      }
      console.log(dataset)
      // this.showPayDialog = false
      PostOnlinePayOrder(dataset).then(res => {
        this.$toast.clear()
        const data = res.data
        if (data.status_code === 200) {
          // console.log(data.data)
          if (type === 3) { // 处理支付宝结果
            const result = data.data
            console.log(result, '放到连接上的数据')
            if (isWechat()) {
              this.$router.push({
                name: 'payTips',
                query: {
                  payment: JSON.stringify(result)
                }
              })
            } else {
              this.$refs.alipayCases.alipayData = data.data
              this.$refs.alipayCases.alipayData.biz_content = JSON.stringify(data.data.biz_content)
              this.$refs.alipayCases.submitData()
            }
          } else if (type === 4) { // 处理微信结果
            this.showDialog = false
            this.showPayDialog = false
            location.href = data.data.mweb_url
          }
        } else {
          this.$toast.fail({
            message: data.message,
            duration: 1500
          })
        }
      })
    },
    // 确认充值
    rechargeEvent() {
      this.$toast.loading({
        duration: 10000,
        mask: true,
        message: '正在充值...'
      })
      const formData = this.formData
      if (this.paymentWay === '1') {
        formData.pay_time = undefined
      }
      addUserRecharge(formData).then(res => {
        this.$toast.clear()
        const data = res.data
        if (data.status_code === 200) {
          this.showPayDialog = false
          this.showDialog = false
          this.$toast.success({
            message: data.message,
            duration: 1500
          })
          // 充值成功重新获取余额数据
          this.getUserAccountInfoFn()
        } else {
          this.$toast.fail({
            message: data.message,
            duration: 1500
          })
        }
      })
    },
    // 在线充值 2手机支付宝 3PC支付宝 4微信
    rechargeOnlineEvent(type) {
      this.$toast.loading({
        duration: 10000,
        mask: true,
        message: '正在跳转...'
      })
      const formData = this.formData
      const dataset = {
        pay_type: type,
        pay_fee: formData.pay_fee
      }
      postAddRechargeByPay(dataset).then(res => {
        this.$toast.clear()
        const data = res.data
        if (data.status_code === 200) {
          if (type === 2) { // 处理支付宝结果
            const result = data.data
            // console.log(result, '放到连接上的数据')
            if (isWechat()) {
              this.$router.push({
                name: 'payTips',
                query: {
                  payment: JSON.stringify(result)
                }
              })
            } else {
              this.$refs.alipayCases.alipayData = data.data
              this.$refs.alipayCases.alipayData.biz_content = JSON.stringify(data.data.biz_content)
              this.$refs.alipayCases.submitData()
            }
          } else if (type === 4) { // 处理微信结果
          }
        } else {
          this.$toast.fail({
            message: data.message,
            duration: 1500
          })
        }
      })
    },
    // 选择了收款账号
    onSelect() {
      const val = this.formData.shop_account_number_id
      const accountList = this.accountList
      let item
      accountList.forEach(account => {
        if (account.shop_account_number_id === val) {
          item = account
        }
      })
      console.log(val, item)
      const shopAccountInfo = this.shopAccountInfo
      shopAccountInfo.shop_account_name = item.account_name
      shopAccountInfo.shop_account_bank = item.account_bank
      shopAccountInfo.shop_account = item.account_number
      shopAccountInfo.name = item.name
      this.shopAccountInfo = shopAccountInfo
      this.formData.shop_account_number_id = val
    },
    // 清空数据
    clearData() {
      this.formData.balance_fee = undefined
      this.formData.pay_fee = undefined
      this.formData.remark = undefined
      this.formData.shop_account_number_id = undefined
    }
  }
}
</script>
<style lang="scss">
  @import "src/styles/mixin.scss";
  .select{
    .mu-input-line{
      background: transparent!important;
    }
    .mu-input-focus-line{
      background: transparent!important;
    }
    .van-cell__value{
      opacity: 0!important;
      input{
        color: #fff!important;
      }
    }
  }
  .disabled{
    .van-field__control:disabled{
      color: #b9b9b9!important;
    }
  }
  .van-popup--bottom{
    width: 100.3% !important;
  }
  .dialog{
    .btn-mini{
      font-size: pxCalc(12px);
      line-height: pxCalc(24px);
      height: pxCalc(24px);
    }
    .van-radio{
      overflow: visible!important;
      margin-top: pxCalc(-2px) !important;
    }
    .van-radio__input{
      height: auto!important;
      font-size: pxCalc(22px) !important;
    }
    .van-cell{
      padding:8px 0!important;
      .van-cell__title{
        font-size: pxCalc(14px)!important;
        color: #666!important;
      }
    }
    .van-hairline--top-bottom::after{
      border: none!important;
    }
  }
</style>
<style scoped lang="scss">
  @import "src/styles/mixin.scss";
  .dialog{
    padding: 0 pxCalc(20px);
    .dialog-title{
      line-height: pxCalc(50px);
      height: pxCalc(50px);
      font-size: pxCalc(17px);
      color: #363b43;
      .icon-close{
        width: pxCalc(50px);
        height: pxCalc(50px);
        line-height: pxCalc(50px);
        text-align: center;
        color: #b5b5b5;
        font-size: pxCalc(18px);
        transform: translateX(34%);
      }
    }
    .dialog-content{
      border-top: pxCalc(1px) solid #eee;
      padding: pxCalc(23px) 0 pxCalc(30px);
      .item{
        margin-bottom: pxCalc(30px);
        font-size: pxCalc(14px);
        color: #666;
        .icon{
          font-size: pxCalc(20px);
          margin-right: pxCalc(5px);
          vertical-align: pxCalc(-3px);
        }
        .price{
          font-size: pxCalc(15px);
        }
        &:last-child{
          margin-bottom: 0;
        }
        .disabled{
          .van-field__control:disabled{
            color: #999!important;
          }
        }
      }
    }
    .dialog-content2{
      margin-bottom: pxCalc(10px);
      .select{
        position: relative;
        &-con{
          position: absolute;
          top: 0;
          left: 90px;
          font-size: pxCalc(14px);
        }
      }
      .waitPay{
        font-size: pxCalc(14px);
        margin-bottom: pxCalc(10px);
        .inline{
          display: inline-block;
        }
        .unit{
          font-size: pxCalc(12px);
        }
        .price{
          font-size: pxCalc(17px);
        }
        .balance-num{
          margin-left: pxCalc(20px);
          color: #666;
          font-size: pxCalc(14px);
        }
      }
      .balance{
        margin-top: pxCalc(30px);
        margin-bottom: pxCalc(150px);
        border-bottom: 1px solid #eee;
      }
    }
    .dialog-bottom{
      padding-bottom: pxCalc(10px);
      .btn{
        width: 100%;
        text-align: center;
        line-height: pxCalc(45px);
        height: pxCalc(45px);
        font-size: pxCalc(15px);
        margin-left: 0;
      }
    }
  }
</style>
